import useUser from '@/store/user'
import type { IRouter } from '@/global/type/menu'
import { localCache } from '@/utils/storage.ts'
import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'
import initRouter from './init'
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/Login/index.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/index.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

function addRouter() {
  const menu: IRouter[] = localCache.getCache('menu') ?? ''
  const arr = initRouter(menu)
  arr?.forEach((item) => {
    router.addRoute('main', item)
  })
}
addRouter()
router.beforeEach(async (to, from, next) => {
  const user = useUser()
  const token = localCache.getCache('token')
  if (user.user.menu.length === 0 && token) {
    const res = await user.getterUserInfoAysnc(token)
    user.user.name = res.username
    user.user.avatar = res.avatar
    user.user.menu = res.routes
    localCache.setCache('menu', res.routes)
    next()
  } else {
    next()
  }
})

export default router
